package exhibition.app.nexd.cn.presenter;

import android.content.Context;
import android.database.Cursor;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;

import com.squareup.okhttp.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;
import java.util.regex.Pattern;

import exhibition.app.nexd.cn.R;
import exhibition.app.nexd.cn.application.NexdApplication;
import exhibition.app.nexd.cn.model.OrderForm;
import exhibition.app.nexd.cn.ui.ivew.ILoginActivityView;
import exhibition.app.nexd.cn.utils.APIUtils;
import exhibition.app.nexd.cn.utils.MySQLiteOpenHelper;
import exhibition.app.nexd.cn.utils.OkHttpClientManager;
import exhibition.app.nexd.cn.utils.Utils;

/**
 * Login presenter
 * <p/>
 * Created by wangxu on 16/4/21.
 */
public class LoginPresenter extends BasePresenter<ILoginActivityView> {

    private Pattern pattern;

    TimeOut authTimeOut;


    public LoginPresenter(Context context, ILoginActivityView iView) {
        super(context, iView);
        pattern = Pattern.compile(context.getString(R.string.match_phone_number));
    }

    //做本地手机号码格式验证
    public void checkPhone(String phone) {
        if (TextUtils.isEmpty(phone)) {
            iView.showToast("手机号不能为空");
        } else if (!pattern.matcher(phone).matches()) {
            iView.showToast("手机号格式有误");
        } else {
            iView.onCheckPhoneSuccess();
            getSMSCode(phone);
        }
    }



    private String getSMSCode(String phoneNumber) {
        authTimeOut = new TimeOut(60000, 1000);
        authTimeOut.start();
        StringBuilder getSMSCode = new StringBuilder();
        getSMSCode.append(APIUtils.GET_SMS_CODE)
                .append("&phoneCode=")
                .append(Utils.getDeviceId(context))
                .append("&phoneNumber=")
                .append(phoneNumber);
        Log.i("getSMSCode", getSMSCode.toString());
        OkHttpClientManager.postAsyn(getSMSCode.toString(), (OkHttpClientManager.Param[]) null, new OkHttpClientManager.ResultCallback<String>() {
            @Override
            public void onError(Request request, Exception e) {
                iView.onGetSMSCodeFailed();
                iView.showToast("当前网络状况不佳,请稍后重试");
                destoryTimer();
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject smsCodeObject = new JSONObject(response);
                    if (smsCodeObject.getBoolean("isSuccess")) {
                        if (!TextUtils.isEmpty(smsCodeObject.getString("smsCode"))) {
                            iView.onGetSMSCodeSuccess(smsCodeObject.getString("smsCode"));
                            destoryTimer();
                        }
                    } else {
                        iView.showToast(smsCodeObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    iView.showToast("数据解析异常");
                    e.printStackTrace();
                }
            }
        });

        return "";
    }

    public void userLogin(final String phoneNumber, String codes) {
        //登录用户，新用户，跳转新用户信息填写界面，老用户，下发userId,跳转主界面
        StringBuffer doUserLogin = new StringBuffer();
        doUserLogin.append(APIUtils.USER_LOGIN)
                .append("&smsCode=")
                .append(codes)
                .append("&phoneCode=")
                .append(Utils.getDeviceId(context))
                .append("&phoneNumber=")
                .append(phoneNumber);
        Log.i("doUserLogin", doUserLogin.toString());
        OkHttpClientManager.postAsyn(doUserLogin.toString(), (OkHttpClientManager.Param[]) null, new OkHttpClientManager.ResultCallback<String>() {
            @Override
            public void onError(Request request, Exception e) {
                iView.showToast("当前网络状况不佳,请稍后重试");
            }

            @Override
            public void onResponse(String response) {
                try {
                    Log.i("response", response);
                    JSONObject userObject = new JSONObject(response);
                    if (userObject.getBoolean("isSuccess")) {
                        if (userObject.getBoolean("isNewUser")) {
                            NexdApplication.getInstance().setPhoneNum(phoneNumber);
                        } else {
                            NexdApplication.getInstance().setUserId(userObject.getInt("userId"));
                        }
                        iView.onUserLoginSuccess(userObject.getBoolean("isNewUser"));
                    } else {
                        iView.showToast(userObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    iView.showToast("数据解析异常");
                    e.printStackTrace();
                }
            }
        });
    }


    //验证码倒计时
    class TimeOut extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public TimeOut(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            iView.onTimerChanged(false, millisUntilFinished / 1000 + "秒后重新获取验证码");
        }

        @Override
        public void onFinish() {
            iView.onTimerChanged(true, "重新获取验证码");
        }

    }

    public void destoryTimer() {
        if (authTimeOut != null) {
            authTimeOut.cancel();
            authTimeOut = null;
        }
    }
}
